package com.xgp.company.tool;
/**
 * JDBC工具类，读取配置文件
 */

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;


public class JDBCUtilsConfig {

	//定义的连接对象
	private static Connection con;
	//驱动
	private static final String dirverClass = "com.mysql.jdbc.Driver";
	//数据库的地址
	private static String url;
	//数据库的用户名
	private static String username;
	//数据库的密码
	private static String password;

	//静态代码块读取配置文件
	static {
		//读取配置文件
		readConfig();
		try {
			Class.forName(dirverClass);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			String newUrl = url.substring(0,url.lastIndexOf('/')) + "/";
//			System.out.println(newUrl);
			con = DriverManager.getConnection(newUrl,username,password);

			//创建数据库
			Statement stmt = con.createStatement();

			int end = url.indexOf('&');
			String data = null;
			if(end == -1) {
				data = url.substring(url.lastIndexOf('/') + 1);
			}else {
				data = url.substring(url.lastIndexOf('/') + 1,end);
			}

			String sql = "CREATE DATABASE IF NOT EXISTS " + data +" DEFAULT CHARACTER SET = 'utf8' ";

			stmt.executeUpdate(sql);

			stmt.close();
			System.out.println(data + "数据库创建成功");
			//重新获取连接
			con = DriverManager.getConnection(url,username,password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	private static void readConfig() {
		//使用反射技术获取文件的输入流
		InputStream in = JDBCUtilsConfig.class.getClassLoader().getResourceAsStream("database.properties");
		//解析properties的类
		Properties pro = new Properties();
		try {
			//读流
			pro.load(in);
		} catch (IOException e) {
			e.printStackTrace();
		}
		//获取值
		username = pro.getProperty("username");
		url = pro.getProperty("url");
		password = pro.getProperty("password");
	}

	//返回连接对象
	public static Connection getConnection() {
		return con;	
	}

	//测试是否连接数据库成功
	public static void main(String[] args) {
		Connection con = JDBCUtilsConfig.getConnection();
		System.out.println(con);
	}
}
